//
//  pickerView.swift
//  uiKit-demo
//
//  Created by 陈澎 on 2025/1/6.
//

import UIKit

class PickerViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
    let colors = ["Red", "Green", "Blue", "Yellow"]
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(white: 1, alpha: 1)
        // 加载
        let loading = UIActivityIndicatorView(style: .large)
        loading.center = self.view.center
        loading.startAnimating()
        self.view.addSubview(loading)
        let pickerView = UIPickerView(frame: CGRect(x:20, y: 20, width: 280, height: 200))
        let colorPicker = UIPickerView(frame: CGRect(x:20, y: 240, width: 280, height: 200))
        Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { timer in
            loading.stopAnimating()
            // 设置代理-需要添加协议UIPickerViewDelegate， UIPickerViewDataSource
            pickerView.delegate = self
            pickerView.dataSource = self
            colorPicker.tag = 1
            self.view.addSubview(pickerView)
            
            // 颜色处理
            colorPicker.dataSource = self
            colorPicker.delegate = self
            // 标记picker可以实现多个picker
            colorPicker.tag = 2
            self.view.addSubview(colorPicker)
            
        }
    }
   
    // 分组数
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        if pickerView.tag == 2 {
            return 1
        }
        return 2
    }
    
    // 这个协议方法需要返回选择器控件每个分组的行数
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        if pickerView.tag == 2 {
            return colors.count
        }
        return 10
    }
    
    // 这个协议方法需要返回每个分组中每行数据的标题
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.textAlignment = .center
        // 字体大小和样式
        label.font = UIFont.boldSystemFont(ofSize: 20)
        
        if pickerView.tag == 2 {
            label.text = colors[row]
            switch colors[row] {
            case "Red":
                label.textColor = .red
            case "Green":
                label.textColor = .green
            case "Blue":
                label.textColor = .blue
            default:
                label.textColor = .black
            }
            return label
        }
        label.text = "第\(component + 1)组第\(row)行"
        return label
    }
}
